import qrcode
import io
import base64
from flask import Blueprint, request, jsonify, send_file, session, redirect, url_for, render_template
from models import db, Product, RepairRecord, User
from flask_login import login_required, current_user
from flask import send_file
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.utils import ImageReader
from reportlab.lib.colors import yellow, black
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from flask import request  # 新增导入

# 注册中文字体（只需做一次，放在文件开头即可）
pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttc'))  # 路径需为你的字体文件实际路径

import tempfile
import os
import socket

bp = Blueprint('equipment_qrcode', __name__)

# 1. 生成二维码图片接口（批量）
@bp.route('/generate_qrcodes', methods=['GET', 'POST'])
# @login_required
def generate_qrcodes():
    if request.method == 'POST':
        device_ids = request.form.get('device_ids')
        print(f'QRcode p30 device_ids={device_ids}')
        if device_ids:
            import json
            device_ids = json.loads(device_ids)
            print(f'QRcode p34 post device_ids={device_ids}')
        else:
            device_ids = []
    else:
        # GET 请求支持 device_ids=1,2,3
        ids_str = request.args.get('device_ids', '')
        device_ids = [int(i) for i in ids_str.split(',') if i.strip().isdigit()]
        print(f'QRcode p42 get device_ids={device_ids}')
    
    print(f"p43 [DEBUG] 总设备ID数量: {len(device_ids)}")
    # 生成临时PDF文件
    with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_pdf:
        c = canvas.Canvas(tmp_pdf.name, pagesize=A4)
        width, height = A4
        x, y = 50, height - 200  # 初始位置
        label_width = 400
        label_height = 180
        for idx, device_id in enumerate(device_ids):
            # 画黄色背景
            c.setFillColor(yellow)
            c.rect(x, y, label_width, label_height, fill=1, stroke=0)
            # 画黑色边框
            c.setStrokeColor(black)
            c.rect(x, y, label_width, label_height, fill=0, stroke=1)
            c.setFillColor(black)
            c.setFont("Helvetica-Bold", 14)
            # 设备信息（需从数据库获取）
            device = Product.query.get(device_id)
            c.setFont("msyh", 14)  # 用中文字体
            c.drawString(x+10, y+label_height-155, f"设备ID: {device.id}")
            c.drawString(x+10, y+label_height-30, f"名  称: {device.product_name}")
            c.drawString(x+10, y+label_height-55, f"科  室: {device.department_name}")
            c.drawString(x+10, y+label_height-80, f"品  牌: {device.manufacturer}")
            c.drawString(x+10, y+label_height-105, f"型  号: {device.model}")
            c.drawString(x+10, y+label_height-130, f"医院: {device.org_short_name_c}")
           
            # 生成二维码信息
            # 生成二维码信息
            serverIP = get_local_ip()
            portNO = "80"  # 确保端口与服务器配置一致
            url = f"http://{serverIP}:{portNO}/equipment/repair/{device_id}"
            print(f'QRcode p69 url={url}')
            img = qrcode.make(url)
            buf = io.BytesIO()
            img.save(buf, format='PNG')
            buf.seek(0)
            c.drawImage(ImageReader(buf), x+260, y+30, width=120, height=120)
            # 右下角小字
            c.setFont("msyh", 10)  # 用中文字体
            c.drawString(x+label_width-80, y+10, "微信扫一扫报修")
            # 下一个标签位置
            y -= (label_height + 30)
            if y < 100:
                c.showPage()
                y = height - 200
        c.save()
        pdf_path = tmp_pdf.name

    # 返回PDF文件
    return send_file(pdf_path, as_attachment=True, download_name="设备报修二维码2.pdf")
    

# 2. 报修页面（扫码后跳转）
@bp.route('/repair/<int:device_id>', methods=['GET', 'POST'])
def repair_page(device_id):
    # 未登录先跳转登录
    if not current_user.is_authenticated:
        session['after_login'] = url_for('equipment_qrcode.repair_page', device_id=device_id)
        return redirect(url_for('login_redirect'))
    device = Product.query.get(device_id)
    if not device:
        return "设备不存在", 404
    if request.method == 'POST':
        desc = request.form.get('fault_desc')
        reporter = request.form.get('reporter')
        record = RepairRecord(
            product_id=device.id,
            org_name=device.org_short_name_c,
            department=device.department_name,
            product_name=device.product_name,
            brand=device.manufacturer,
            fault_desc=desc,
            reporter=reporter,
            status='待响应',
            create_time=datetime.now()
        )
        db.session.add(record)
        db.session.commit()
        return "报修提交成功！"
    # GET请求，显示表单
    # 只读信息
    readonly_fields = {
        "设备名称": device.product_name,
        "所属机构": device.org_short_name_c,
        "所属科室": device.department_name,
        "通用类型": device.equipment_type,
        "品牌": device.manufacturer
    }
    # 渲染HTML表单
    html = "<h3>设备报修</h3>"
    for k, v in readonly_fields.items():
        html += f"<div><b>{k}：</b>{v}</div>"
    html += '''
    <form method="post">
        <div>
            <label>故障描述：</label>
            <textarea name="fault_desc" required style="width:300px;height:80px;"></textarea>
        </div>
        <div>
            <label>报修人：</label>
            <input type="text" name="reporter" required style="width:200px;">
        </div>
        <button type="submit">提交报修</button>
    </form>
    '''
    return html



# 4. 前端按钮（在设备台账页面，调用/generate_qrcodes接口，展示二维码图片）
# 你可以在Dash页面加一个按钮，点击后获取当前筛选设备id，调用/generate_qrcodes接口，弹窗展示所有二维码。

# 5. 记得在app.py注册蓝图
# app.register_blueprint(equipment_qrcode.bp, url_prefix='/equipment')


# 在模块顶部添加IP获取逻辑
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        return s.getsockname()[0]
    except Exception:
        return '127.0.0.1'